<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span>{{ userId }}</span>
        <el-button :type="!state?'success':'danger'" text @click="connection">
          <span v-if="!state">开始</span>
          <span v-else>结束</span>
          聊天
        </el-button>
      </div>
    </template>
    <el-card shadow="never">
      <el-empty v-if="msgList.length < 1" description="暂无消息" :style="'height:'+ windowHeight"/>
      <el-scrollbar v-else ref="scrollbarRef" :height="windowHeight" always>
        <el-timeline>
          <el-timeline-item v-for="msg in msgList"
                            :timestamp="(msg.toUserId === userId ? toUserId : userId) + ' ' + msg.time"
                            placement="top"
                            :color="msg.toUserId === userId ? '#0bbd87' : 'primary'">
            <el-text style="white-space: pre-line">{{ msg.content }}</el-text>
          </el-timeline-item>
        </el-timeline>
      </el-scrollbar>
    </el-card>
    <el-form ref="formRef" :model="from" :rules="fromRules" @keyup.enter.ctrl="sendMsg" :disabled="!state"
             style="margin-top: 20px">
      <el-form-item prop="content">
        <el-input
            type="textarea"
            v-model="from.content"
            placeholder="请输入消息，按<Ctrl+Enter>发送..."
            :rows="3"
            resize="none"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="sendMsg">发送消息</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts" setup>
import {nextTick, reactive, ref, watch} from "vue";
import {close, creatWebSocket, send} from "../../utils/websocket";
import {ElForm, ElScrollbar} from "element-plus";

const props = defineProps({
  userId: String,
  toUserId: String
})

let windowHeight = window.innerHeight - 350 + 'px';

const formRef = ref<InstanceType<typeof ElForm>>()
const scrollbarRef = ref<InstanceType<typeof ElScrollbar>>()

let state = ref<boolean>(false)
let msgList = ref<any[]>([])

const from = reactive({
  toUserId: props.toUserId,
  time: new Date().toLocaleDateString() + " " + new Date().toLocaleTimeString(),
  content: ""
})

const fromRules = ref({
  content: [{required: true, message: "请输入消息", trigger: 'submit'}],
})

const connection = () => {
  if (!state.value) {
    creatWebSocket("ws://localhost:8080/websocket/user/" + props.userId, msgList);
  } else {
    close()
  }
  state.value = !state.value;
}

const sendMsg = () => {
  formRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false
    }
    send(from);
    msgList.value.push(JSON.parse(JSON.stringify(from)));
    formRef.value!.resetFields()
  })
}

watch(msgList, (newValue, oldValue) => {
      nextTick(() => {
        scrollbarRef.value!.setScrollTop(scrollbarRef.value!.wrapRef.scrollHeight);
      })
    }, {deep: true}
)
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
